<?php

namespace controller;

/**
 * Description of Cart
 *
 * @author Damian
 */
class Cart extends Shop {

    /**
     *
     * @var \library\Basket
     */
    private $basket;

    /**
     *
     * @var \model\TblOrder
     */
    private $order;

    public function __construct($options = array()) {
        parent::__construct($options);
        $session = \library\Registry::get("session");
        // $session->erase("order");
        $this->basket = ($session->get("basket")) ? $session->get("basket") : new \library\Basket();
        $view = $this->getActionView();
        $view->set("basket", $this->basket);
        $this->order = ($session->get("order")) ? $session->get("order") : new \model\TblOrder();
        //  var_dump($this->order);
        $customer = $session->get("customer");
        if ($customer){
            $this->order->PaymentID=$customer->DefaultPayment;
            $this->order->AdressID=$customer->DefaultAdress;
            $this->order->DeliveryMethodID=$customer->DefaultDelivery;
        }
        $this->order->CustomerID = $customer;
        $session->set("order", $this->order);
    }

    public function index() {
        //  var_dump($this->order);
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "Zawartość Twojego koszyka");
        $products = $this->basket->getProducts();
        $view = $this->getActionView();
        $paymentsCriteria = new \model\Criteria();
        $paymentsCriteria->from(\model\TblPayment::getModel()->getTable())
                ->where(\model\TblPayment::SHOP_ID, "=", $this->shop->ShopID);
        $payments = \model\TblPayment::getModel()->all($paymentsCriteria);
        $paymentsDataTable = new \model\DataTable($payments);

        $deliveryCriteria = new \model\Criteria();
        $deliveryCriteria->from(\model\TblDeliveryMethod::getModel()->getTable())
                ->where(\model\TblDeliveryMethod::SHOP_ID, "=", $this->shop->ShopID);
        $deliveryMethods = \model\TblDeliveryMethod::getModel()->all($deliveryCriteria);
        $deliveryCriteriaDataTable = new \model\DataTable($deliveryMethods);
        //var_dump($paymentsDataTable->getModelData(true));
        $view->set("deliveryMethods", $deliveryCriteriaDataTable->getModelData(true));
        $view->set("payments", $paymentsDataTable->getModelData(true));
        $view->set("products", $products);
        $view->set("order", $this->order);
        $this->render();
       
    }

    public function adress() {
        $session = \library\Registry::get("session");
        if (!$session->get("customer") && !$session->get("login")){
            $session->set("last_url",\library\RequestMethods::server("request_uri"));
            $this->redirect($this->shop->URL."/users/login");
        }
        if (!$this->order->DeliveryMethodID || !$this->order->PaymentID || $this->basket->getItemCount() == 0) {
            $this->redirect($this->shop->URL . "/cart");
        }
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "Wybór adresu dostawy");
        $view = $this->getActionView();
        if (!$this->person) {
            $view->set("notLogged", true);
            $this->render();
            exit();
        }
        //dodawanie adresu
        $register = "inputRegister";
        $postCodeCriteria = new \model\Criteria();
        $postCodeCriteria->from(\model\TblPostCode::getModel()->getTable())
                ->where(\model\TblPostCode::CODE, "=", \library\RequestMethods::post($register . "PostCode"))
                ->where(\model\TblPostCode::STREET_ID, "=", \library\RequestMethods::post($register . "Street", 1), false, " and ");
        if (\library\RequestMethods::post($register . "City")) {
            $postCodeCriteria->where(\model\TblPostCode::CITY_ID, "=", \library\RequestMethods::post($register . "City"), false, " and ");
        }
        $postCode = \model\TblPostCode::getModel()->first($postCodeCriteria);
        if ($postCode && \library\RequestMethods::post($register . "Number")) {
            $city = (\library\RequestMethods::post($register . "City")) ? \library\RequestMethods::post($register . "City") : $postCode->CityID;
            $adress = new \model\TblAdress([
                \model\TblAdress::POST_CODE_ID => $postCode,
                \model\TblAdress::NUMBER => \library\RequestMethods::post($register . "Number"),
                \model\TblAdress::DEFAULT_ADRESS => 1,
                \model\TblAdress::PERSON_ID => $this->person->PersonID,
                \model\TblAdress::STREET_ID => \library\RequestMethods::post($register . "Street", 1),
                \model\TblAdress::CITY_ID => $city
            ]);
            $adress->save();
        }

        $adressCriteria = new \model\Criteria();
        $adressCriteria->from(\model\TblAdress::getModel()->getTable())
                ->join(\model\TblPerson::getModel())
                ->join(\model\TblStreet::getModel())
                ->join(\model\TblCity::getModel())
                ->join(\model\TblPostCode::getModel())
                ->where(\model\TblPersonAdress::PERSON_ID, "=", $this->person->PersonID, \model\TblAdress::getModel()->getTable());
        $adresses = \model\TblPersonAdress::getModel()->all($adressCriteria);
        if (sizeof($adresses) == 0) {
            $view->set("noAdress", true);
        } elseif (sizeof($adresses) == 1) {
            // var_dump(\library\ArrayMethods::first($adresses));
            $view->set("adress", \library\ArrayMethods::first($adresses));
            $this->order->AdressID = \library\ArrayMethods::first($adresses)->AdressID;
           $session->set("order", $this->order);
        } else {
            $modelData = new \model\DataTable($adresses, false);
            $view->set("adresses", $modelData->getModelData(false));
        }
        $this->render();
    }

    public function buy() {
        $session = \library\Registry::get("session");
        if (!$session->get("customer") && !$session->get("login")){
            $session->set("last_url",\library\RequestMethods::server("request_uri"));
            $this->redirect($this->shop->URL."/users/login");
        }
        if (!$this->order->AdressID) {
            $this->order->AdressID = \library\RequestMethods::post("adressID");
        }        
        $session->set("order", $this->order);
        if (!$this->order->DeliveryMethodID || !$this->order->PaymentID || $this->basket->getItemCount() == 0 || !$this->order->AdressID) {
            $this->redirect($this->shop->URL . "/cart");
        }
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "Podsumowanie koszyka i zakup");
        $products = $this->basket->getProducts();
        $view = $this->getActionView();
        $view->set("products", $products);
        $adressCriteria = new \model\Criteria();
         $customer = $session->get("customer");
         $view->set("customer",$customer);
        $adressCriteria->from(\model\TblAdress::getModel()->getTable())
                ->join(\model\TblPerson::getModel())
                ->join(\model\TblStreet::getModel())
                ->join(\model\TblCity::getModel())
                ->join(\model\TblPostCode::getModel())
                ->where(\model\TblPersonAdress::ADRESS_ID, "=", $this->order->AdressID, \model\TblAdress::getModel()->getTable());
        $adress = \model\TblPersonAdress::getModel()->first($adressCriteria);
        $payment = \model\TblPayment::getModel()->getByPrimaryKey($this->order->PaymentID);
        $delivery = \model\TblDeliveryMethod::getModel()->getByPrimaryKey($this->order->DeliveryMethodID);
        $view->set("adress", $adress);
        $view->set("payment", $payment);
        $view->set("delivery", $delivery);
        $this->render();
    }

    public function buynow() {
        $session = \library\Registry::get("session");
        if (!$session->get("customer") && !$session->get("login")){
            $session->set("last_url",\library\RequestMethods::server("request_uri"));
            $this->redirect($this->shop->URL."/users/login");
        }
        if (!$this->order->AdressID) {
            $this->order->AdressID = \library\RequestMethods::post("adressID");
        }
        if (!$this->order->DeliveryMethodID || !$this->order->PaymentID || $this->basket->getItemCount() == 0 || !$this->order->AdressID) {
            $this->redirect($this->shop->URL . "/cart");
        }  
        $productKeys = $this->basket->getProducts();
        $productsCriteria = new \model\Criteria();
        $productsCriteria->from(\model\TblProduct::getModel()->getTable())
                ->in(\model\TblProduct::ID, $this->basket->getProductKeys());
        $products = \model\TblProduct::getModel()->all($productsCriteria);
        foreach($products as &$product){
            $product->Amount = $product->Amount-$productKeys[$product->ProductID]["Amount"];
            $product->save();            
        }
       //$delivery->Price+$basket->getTotalCost()
        $this->order->ShopID=  $this->shop->ShopID;
        $this->order->Status=5;
        $this->order->OrderDate=date("Y-m-d H:i:s");
        $delivery = \model\TblDeliveryMethod::getModel()->getByPrimaryKey($this->order->DeliveryMethodID);
         
        $customer = $session->get("customer");
        
        $this->order->TotalCost = $delivery->Price + $this->basket->getTotalCost();
        if ($customer->Discount>0){
            $this->order->TotalCost = $this->order->TotalCost/100*$customer->Discount;
        }
        $OrderID = $this->order->save();
        foreach ($productKeys as $key => $value) {
            $productOrder = new \model\TblProductOrder(
                    [
                \model\TblProductOrder::PRODUCT_ID => $key,
                \model\TblProductOrder::ORDER_ID => $OrderID,
                \model\TblProductOrder::AMOUNT => $value["Amount"]
            ]);
            $productOrder->save();
        }
         $person = $session->get("login");
        $view = $this->getActionView();
        $controller = new Office();
        $phpWord = $controller->getBasket(true);
        // Save File
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $filename = "zawartość koszyka sklepu " . $this->shop->Name . ".docx";
        $objWriter->save($filename);
        $mailBody = "Dziękujemy za dokonanie zakupów w naszym sklepie. W załączniku zamieściliśmy zestawienie Twojego koszyka.<br/>";
        $payment = \model\TblPayment::getModel()->getByPrimaryKey($this->order->PaymentID);        
        $mailBody.="Jako metodę płatności wybrałeś " . $payment->Name . ". " . $payment->MailContent . "<br>";
        $mailBody.="Jako metodę dostawy wybrałeś " . $delivery->Name . ". " . $delivery->Description . "<br>";
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "Dziękujemy za zakupy");
        try {
            $mail = new \library\Mail();
            $mail->AddAddress($person->Email, $person->Name." ".$person->Surname);
            $mail->sendEmail("podsumowanie zakupów", $mailBody, "sprzedawca", $filename);
            $view->set("success", "Doknałeś zakupu, niebawem otrzymasz wiadomość email z bardziej szczegółowymi informacjami");
            $session->set("order", null);
            $session->set("adress", null);
            $session->set("basket", null);
            $view->set("basket", null);
            $layoutView->set("basket", new \library\Basket());
        $session->set("payment", null);
        $session->set("delivery", null);
        } catch (\library\exceptions\MailException $e) {
             $view->set("error", $e->getMessage());
        }
        $this->render();
    }

}
